package com.jackrain.nea.fc.dl.mapper;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;
import com.jackrain.nea.fc.utils.ObjectToUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author kangcong
 * @date 2018/08/15
 **/
@Mapper
public interface ViewDLTPurOutBillIdMapper {

    String FIELDS="ID," +
            "OUT_BILL_NO," +
            "OUT_BILL_DATE," +
            "CP_C_STORE_ID," +
            "CP_C_STORE_ECODE," +
            "CP_C_STORE_ENAME," +
            "CP_C_SUPPLIER_ID," +
            "CP_C_SUPPLIER_ECODE," +
            "CP_C_SUPPLIER_ENAME," +
            "ISACTIVE," +
            "OWNERNAME," +
            "CREATIONDATE," +
            "MODIFIERNAME," +
            "MODIFIEDDATE";

    @Select("SELECT " + FIELDS + " FROM DL_T_PUR_OUT_BILL_ID  WHERE OUT_BILL_NO = #{outbillno}")
    HashMap selectDataByOutBillNo(@Param("outbillno") String outbillno);

    //查询是否已存在
    @Select("SELECT COUNT(1) FROM DL_T_PUR_OUT_BILL_ID WHERE OUT_BILL_NO=#{billno}")
    int selectBillIdCount(@Param("billno") String billno);

    @Delete("DELETE FROM DL_T_PUR_OUT_BILL_ID WHERE  OUT_BILL_NO=#{billno}")
    int deleteFromBillId(@Param("billno") String billno);

    @InsertProvider(type = PurOutBillId.class, method = "insertSql")
    int insert(@Param("tableName") String tableName, @Param("insertKeys") JSONObject insertKeys);

    @Update("UPDATE DL_T_PUR_OUT_BILL_ID SET ISACTIVE='N', MODIFIERNAME=#{modifiername}, MODIFIEDDATE=#{modifieddate} WHERE  OUT_BILL_NO=#{billno}")
    int update(@Param("billno") String billno, @Param("modifiername") String modifiername, @Param("modifieddate") String modifieddate);

    class PurOutBillId{
        public String insertSql(Map<String, Object> para) {

            String tableName = ObjectToUtil.getString(para.get("tableName"), "");
            JSONObject insertKeys = (JSONObject) para.get("insertKeys");

            String sql = new SQL() {
                {
                    Set<String> keySet = insertKeys.keySet();
                    INSERT_INTO(tableName);
                    for (int i = 0; i < insertKeys.size(); i++) {
                        String key = (String) keySet.toArray()[i];
                        if (insertKeys.getString(key) == null) {
                            continue;
                        }
                        VALUES(key, "#{insertKeys." + key + "}");
                    }
                }
            }.toString();

            System.out.print("sql ========>" + sql + "\r");

            return sql;
        }


    }

}
